import http from '@/utils/request.ts'
import type { Doc } from '@/modules/doc/types/doc.ts'

export interface DragRequest {
  targetId: string
  dropType: 'before' | 'after' | 'inner'
}

export const documentApi = {
  // 根据命名空间获取文档
  getByNamespace: async (namespaceId: string) => {
    return http.get<any[]>(`/doc/list?namespaceId=${namespaceId}`)
  },

  // 获取收藏文档列表
  getFavorites: async () => {
    return http.get<any[]>('/doc/list?isFavorite=true')
  },

  // 根据ID获取文档详情
  getById: async (id: string) => {
    return http.get<Doc>(`/doc/${id}`)
  },

  // 创建新文档
  create: async (document: Omit<Doc, 'id' | 'createdTime' | 'updatedTime' | 'children'>) => {
    return http.post<Doc>('/document', {
      name: document.name,
      content: document.content || '',
      parentId: document.parentId,
      sortNo: document.sortNo || 0,
      namespaceId: document.namespaceId,
      permission: document.permission,
      layoutType: document.layoutType,
      isFavorite: document.isFavorite,
      isShowToc: document.isShowToc
    })
  },

  // 更新文档
  update: async (id: string, document: Omit<Doc, 'id' | 'createdTime' | 'updatedTime' | 'children'>) => {
    return http.put<Doc>(`/doc/${id}`, {
      name: document.name,
      content: document.content || '',
      parentId: document.parentId,
      sortNo: document.sortNo || 0,
      namespaceId: document.namespaceId,
      permission: document.permission,
      layoutType: document.layoutType,
      isFavorite: document.isFavorite,
      isShowToc: document.isShowToc
    })
  },

  // 删除文档
  delete: async (id: string) => {
    return http.delete(`/doc/${id}`)
  },

  // 移动文档
  moveDocument: async (documentId: string, newParentId: string | null, sortNo: number) => {
    return http.put<boolean>(`/doc/${documentId}/move`, {
      parentId: newParentId,
      sortNo: sortNo
    })
  },

  // 拖拽文档
  drag: async (id: string, data: DragRequest) => {
    return http.put(`/doc/${id}/drag`, data)
  }
}